<?php if (!defined("MAIN_DIR")) { header("Location: /"); die; }

class User {
	
	private $_id = 0;
	private $_type = 'guest';
	private $_privilege = 'guest';
	private $_login = 'guest';
	private $_name = 'guest';
	private $_db;
	private $_privilege_list;
	
	function __construct ($db){
		
		// init
		$this->_db = $db;
		
		// login by session
		if (isset($_SESSION['userId']) && $_SESSION['userId'] != ''){
			$u = $this->_db->getRow("select `login`,`password` from `users` where `user_id` = '".$_SESSION['userId']."' limit 1");
			if (count($u) > 0)
				$this->login($u['login'],$u['password'],false,true);
		// login by cookie
		} elseif (isset($_COOKIE["_auhash"]) && $_COOKIE["_auhash"] != ""){
			$hash = $_COOKIE['_auhash'];
			$r_user = $this->_db->getRow("select * from `remember_users` where `hash` = '$hash' limit 1");
			if ($r_user){
				if ($r_user['before_time'] > time()){
					$u = $this->_db->getRow("select `login`,`password` from `users` where `user_id` = '".$r_user['user_id']."' limit 1");
					if (count($u) > 0)
						$this->login($u['login'],$u['password'],false,true);
				} else {
					setcookie("_auhash","",-1);
					$this->_db->sendQuery("delete from `remember_users` where `user_id` = '$r_user[user_id]' limit 1");
				}
			}
		}
	}
	
	public function login($login,$password,$remember=false,$by_session=false){
		$auth = false;
		$salt = $this->_db->getCell("select `salt` from `users` where `login` = '".$login."' limit 1");
		
		if ($salt != ""){
			// вход по логину
			if (!$by_session){
				$pass = md5(md5($password).$salt);
			// вход по сессии
			} else {
				$pass = $password;
			}
			
			$auth = $this->_db->getRow("select * from `users` where `login` = '".$login."' and `password` = '".$pass."' limit 1");
			
			if ($auth) {
				
				$_SESSION['userId'] = $auth["user_id"];
				$this->_id = $auth["user_id"];
				$this->_type = $auth["type"];
				$this->_privilege = $auth["privilege"];
				$this->_login = $auth["login"];
				$this->_name = $auth["name"];
				
				$query = "select `project_manage`, `modify_own_records`, `modify_other__records`, `delete_own_records`, `delete_other__records`, `add_records`, `create_users`, `modify_users`, `delete_users`, `add_comments`, `modify_comments`, `delete_comments` from `privileges` where `type` = '".$auth['privilege']."' limit 1";
				$this->_privilege_list = $this->_db->getRow($query);
				
				// ставим куку
				if ($remember){
					
					$before = time() + 1209600;
					$hash = md5($auth["login"].$before);
					$user_agent = $_SERVER['HTTP_USER_AGENT'];
					setcookie("_auhash",$hash,$before,"/");
					
					// remember on 2 week
					$this->_db->sendQuery("insert into `remember_users` values (NULL,'$auth[user_id]','$hash','$before','$user_agent')");
				}
				
				// обновляем время
				$this->_db->sendQuery("update `users` set `last_time` = '".time()."', `last_ip` = '".$_SERVER['REMOTE_ADDR']."' where `user_id` = '".$auth["user_id"]."' limit 1");
				
				return $auth["user_id"];
			} else {
				$this->logout();
			}
		} else {
			$this->logout();
		}
		
		return false;
	}
	
	public function logout(){
		$hash = $_COOKIE['_auhash'] ? $_COOKIE['_auhash'] : 0;
		setcookie("_auhash","",-1,"/");
		$user_id = isset($_SESSION['userId']) ? $_SESSION['userId'] : 0;
		$this->_db->sendQuery("delete from `remember_users` where `user_id` = '$user_id' and `hash` = '$hash' limit 1");
		unset($_SESSION['userId']);
	}
	
	public function Id(){
		return $this->_id;
	}
	public function getLogin(){
		return $this->_login;
	}
	
	public function isUser(){
		return ($this->_type != 'guest');
	}
	public function isUsialUser(){
		return ($this->_type == 'user');
	}
	public function isModerator(){
		return ($this->_type == 'moderator');
	}
	public function isAdmin(){
		return ($this->_type == 'administrator');
	}
	public function getPermission($permission){
		return $this->_privilege_list[$permission];
	}
}
?>